
var player,cursors,element,score,help;
var Preloader = new Phaser.Class({
    Extends:Phaser.Scene,
    initialize:function Preloader(){
        Phaser.Scene.call(this,{key:"preloader"});
    },
    preload:function(){
        this.load.image('tiles','http://q7ojpzo68.bkt.clouddn.com/map.png');
        this.load.tilemapTiledJSON('map','http://q7ojpzo68.bkt.clouddn.com/map.json');
        this.load.spritesheet('dude', 'http://q7ojpzo68.bkt.clouddn.com/dude.png', { frameWidth: 32, frameHeight: 48 });
        this.load.image('star', 'http://q7ojpzo68.bkt.clouddn.com/star.png');

        var loading = this.add.text(16, 16, 'loading:0', {
            fontSize: '18px',
            padding: { x: 440, y: 400 },
            fill: '#ffffff'
        });
        loading.setScrollFactor(0);
        this.load.on("progress",function(progress){
            console.log(progress);
            loading.text='loading:'+(progress*100).toFixed(0)+'%';
        });
    },
    create:function(){ //  Our player animations, turning, walking left and walking right.
        this.anims.create({
            key: 'left',
            frames: this.anims.generateFrameNumbers('dude', { start: 0, end: 3 }),
            frameRate: 10,
            repeat: -1
        });
    
        this.anims.create({
            key: 'turn',
            frames: [ { key: 'dude', frame: 4 } ],
            frameRate: 20
        });
    
        this.anims.create({
            key: 'right',
            frames: this.anims.generateFrameNumbers('dude', { start: 5, end: 8 }),
            frameRate: 10,
            repeat: -1
        });

        this.scene.start('main');
    }
});


var Main = new Phaser.Class({
    Extends: Phaser.Scene,
    initialize: function Main(){
        Phaser.Scene.call(this,{key:'main'});
    },
    create:function(data){
        var map = this.make.tilemap({key:'map'});
        var tileset = map.addTilesetImage('asset','tiles');
    
        var ground = map.createStaticLayer('ground',tileset,0,0);
        var box = map.createStaticLayer('box',tileset,0,0);
        // var grass = map.createStaticLayer('grass',tileset,0,0);
    
        ground.setCollisionByProperty({collides:true});
        box.setCollisionByProperty({collides:true});
    
        var spawnPoint = map.findObject('player',function(obj){return obj.name===''});
        map.setCollision([ 20, 48 ]);
        // player
        player = this.physics.add.sprite(spawnPoint.x,spawnPoint.y-20, 'dude');
        //  Player physics properties. Give the little guy a slight bounce.
        player.setBounce(0.2);
        player.setDamping(false);
        player.setCollideWorldBounds(true);
        // physics
        this.physics.add.collider(player,ground);
        this.physics.add.collider(player,box);
    
        // star
        this.stars = map.createFromObjects('jewel','',{});
        this.starGroup = new Stars(this.physics.world,this,[],this.stars);
    
        this.physics.add.overlap(player,this.starGroup,null,hitStar,this);
        // camera
        var camera = this.cameras.main;
        camera.setBounds(0,0,map.widthInPixels,map.heightInPixels)
        camera.startFollow(player);
    
        // text
        this.score=data.score||0; 
        help = this.add.text(16, 16, 'Score:'+this.score, {
            fontSize: '18px',
            padding: { x: 10, y: 5 },
            fill: '#ffffff'
        });
        help.setScrollFactor(0);
    
        //  Input Events
        cursors = this.input.keyboard.createCursorKeys();
    },
    update:function(){
        if (cursors.left.isDown)
        {
            player.setVelocityX(-160);
    
            player.anims.play('left', true);
        }
        else if (cursors.right.isDown)
        {
            player.setVelocityX(160);
    
            player.anims.play('right', true);
        }else{
            player.setVelocityX(0);
        }
     
        if(cursors.up.isDown&& player.body.blocked.down){
            player.setVelocityY(-440);
        }
    }
});


var GameOver = new Phaser.Class({
    Extends: Phaser.Scene,
    initialize: function GameOver(){
        Phaser.Scene.call(this,{key:'gameover'})
    },
    create: function(data){
        var config1 = {
            x: window.game.config.width / 2-180,
            y: 0,
            text:"YOU WIN!" ,
            style: {
              fontSize: '76px',
              fontFamily: 'Needle',
              fill: '#f08f3f',
              align: 'center'
            }
          }
        this.winTxt = this.make.text(config1)
        this.tweens.add({
            targets: [this.winTxt],//tweens动画目标
            ease: 'Bounce',//运动方式
            y: window.game.config.height / 2-100,// 目标的y坐标,
            duration: 1000,//动画时间
            callbackScope: this,//回调函数的this值
            onComplete: () => {//完成时的回调函数
              setTimeout(() => { this.scene.start('main', {score: data.score}) }, 500)
            }
          })
    }
});


var config = {
    type: Phaser.AUTO,
    width: 1024,
    height: 1024,
    backgroundColor: '#0da1d2',
    physics: {
        default: 'arcade',
        arcade: {
            gravity: {y:600},
            debug: false
        }
    },
    scene:[Preloader,Main,GameOver],
    scale:{
        sacleMode:Phaser.Scale.ScaleModes.WIDTH_CONTROLS_HEIGHT,
        autoCenter: Phaser.Scale.CENTER_BOTH,
    }
}


var game = new Phaser.Game(config);

function hitStar(a,b){
    this.score++;
    help.text='Score:'+this.score;
    b.destroy();
    var stars = this.starGroup.children;
    if(stars.size===0){
        this.scene.start('gameover',{score:this.score});
    }
    // 此处阻止星星与游戏主角之间碰撞检测后续触发
    return false;
}